package org.boge.wxnovel.controller;

import org.apache.commons.io.FileUtils;
import org.boge.wxnovel.bean.Genres;
import org.boge.wxnovel.service.GenresService;
import org.boge.wxnovel.service.NovelDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.IOException;

@Controller
public class CommonController {
    @Autowired
    private NovelDetailService novelDetailService;
    @Autowired
    private GenresService genresService;
    @RequestMapping("/search/{key}/{searchType}/{pageSize}/{pageNum}")
    public String doSearch(@PathVariable String key,
                           @PathVariable Integer pageNum,
                           @PathVariable Integer pageSize,
                           @PathVariable Integer searchType,
                           Model model){
        model.addAttribute("key",key);
        model.addAttribute("searchType",searchType);
        switch (searchType) {
            case 0 -> model.addAttribute("pageInfo", novelDetailService.searchByName(key, pageSize, pageNum));
            case 1 -> model.addAttribute("pageInfo", novelDetailService.searchByDesc(key, pageSize, pageNum));
        }
        return "searchList";
    }

    @RequestMapping("/img/{id}")
    @ResponseBody
    public byte[] getImg(@PathVariable Integer id) throws IOException {
        File coverFile=new File("E:\\boge_\\Documents\\115网盘\\pics",id.toString()+".jpg");
        if(coverFile.exists())
            return FileUtils.readFileToByteArray(coverFile);
        else
            return null;
    }

    @RequestMapping("")
    public String index(Model model){
        model.addAttribute("genresList",genresService.getAllGenres());
        return "index";
    }

    @RequestMapping("/genres/{genresId}/{pageSize}/{pageNum}")
    public String listGenres(Model model,
                          @PathVariable Integer genresId,
                          @PathVariable Integer pageNum,
                          @PathVariable Integer pageSize){
        Genres genres=new Genres();
        genres.setId(genresId);
        if (genresId == 0) {
            model.addAttribute("pageInfo", novelDetailService.getAll(pageSize, pageNum));
            genres.setName("全部小说");
        } else {
            model.addAttribute("pageInfo", novelDetailService.getByGenres(genresId, pageSize, pageNum));
            genres.setName(genresService.getById(genresId).getName());
        }
        model.addAttribute("genres",genres);
        return "list";
    }
}
